package com.t2t.top.gc;

/**
 * Created by yangpengfei on 2016/9/15.
 * <p/>
 * 对象的一次自我拯救
 */
public class FinalizeEscapeGC {
    public static FinalizeEscapeGC SAVE_HOOK = null;

    public void isAlive() {
        System.out.println("yes,I am still alive");
    }

    @Override
    protected void finalize() throws Throwable {
        SAVE_HOOK = this;
        super.finalize();
        System.out.println("finalize method executed!");
    }

    public static void main(String[] args) throws InterruptedException {
        SAVE_HOOK = new FinalizeEscapeGC();

        //自救一次
        SAVE_HOOK = null;
        System.gc();
        //因为finalize方法优先级很低，所以暂停500毫秒
        Thread.sleep(500);
        if (SAVE_HOOK != null) {
            SAVE_HOOK.isAlive();
        } else {
            System.out.println("no, I am dead");
        }

        //下面这段与上面代码完全想通，但是这次却自救失败
        SAVE_HOOK = null;
        System.gc();
        //因为finalize方法优先级很低，所以暂停500毫秒
        Thread.sleep(500);
        if (SAVE_HOOK != null) {
            SAVE_HOOK.isAlive();
        } else {
            System.out.println("no, I am dead");
        }
    }


}
